package com.example.wifimonitor;

import static androidx.core.app.ActivityCompat.startActivityForResult;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.util.Log;

import androidx.core.app.NotificationCompat;

public class WifiReceiver extends BroadcastReceiver {
    private static final String TAG = "WifiReceiver";
    private static final int DELAY_MS = 1000; // 延迟1秒后重新打开WiFi
    private boolean isHandlingWifiState = false; // 是否正在处理WiFi状态

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction() != null && intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
            int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN);
            
            switch (wifiState) {
                case WifiManager.WIFI_STATE_DISABLED:
                    Log.d(TAG, "WiFi已关闭，准备自动重新打开");
                    WifiLog.addLog("WiFi已关闭");
                    // 延迟一段时间后重新打开WiFi
                    new Handler().postDelayed(() -> enableWifi(context), DELAY_MS);
                    
                    // 如果MainActivity正在运行，更新UI
                    if (context instanceof MainActivity) {
                        ((MainActivity) context).updateStatus();
                        ((MainActivity) context).showToast("WiFi已关闭，正在重新打开...");
                    }
                    break;
                    
                case WifiManager.WIFI_STATE_ENABLED:
                    Log.d(TAG, "WiFi已开启");
                    WifiLog.addLog("WiFi已开启");
                    // 如果MainActivity正在运行，更新UI
                    if (context instanceof MainActivity) {
                        ((MainActivity) context).updateStatus();
                    }
                    break;
            }
        }
    }

    // 打开WiFi
    private void enableWifi(Context context) {
        if (isHandlingWifiState) {
            Log.d(TAG, "正在处理WiFi状态，忽略重复请求");
            return;
        }
        
        WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if (wifiManager != null && !wifiManager.isWifiEnabled()) {
            isHandlingWifiState = true;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
                // Android 10及以上版本，先打开主程序再打开WiFi设置面板
                Intent mainIntent = new Intent(context, MainActivity.class);
                mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                context.startActivity(mainIntent);


//                Intent notificationIntent = new Intent(context, MainActivity.class);
//                notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
//                PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
//
//                NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "channel_id")
//                        .setSmallIcon(R.mipmap.ic_launcher)
//                        .setContentTitle("App Name")
//                        .setContentText("点击打开应用")
//                        .setAutoCancel(true)
//                        .setContentIntent(pendingIntent);
//
//                NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
//                manager.notify(1, builder.build());
                
                // 延迟2秒后打开WiFi设置面板
                new Handler().postDelayed(() -> {
                    isHandlingWifiState = false;
                    Log.d(TAG, "重置WiFi处理状态");
                    
                    Intent panelIntent = new Intent(android.provider.Settings.Panel.ACTION_WIFI);
                    panelIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                    context.startActivity(panelIntent);
                    Log.d(TAG, "Android 10及以上版本：打开WiFi设置面板");
                }, 2000);
            } else {
                // Android 9及以下版本，直接打开WiFi
                wifiManager.setWifiEnabled(true);
                Log.d(TAG, "Android 9及以下版本：自动打开WiFi成功");
                
                // 3秒后重置状态标志
                new Handler().postDelayed(() -> {
                    isHandlingWifiState = false;
                    Log.d(TAG, "重置WiFi处理状态");
                }, 3000);
            }
        }
    }
}